package com.wyh.edu.service.impl;

import com.wyh.edu.dao.TokenDao;
import com.wyh.edu.dao.UserDao;
import com.wyh.edu.pojo.Token;
import com.wyh.edu.pojo.User;
import com.wyh.edu.service.AuthCodeServiceFeignClient;
import com.wyh.edu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * @author wuyuhan
 * @date 2021/2/4 23:09
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private TokenDao tokenDao;

    @Autowired
    private AuthCodeServiceFeignClient authCodeServiceFeignClient;

    @Override
    public Token register(String email, String password, String code) {
        //注册前校验：1.是否已注册；2用数据库保存的验证码和从邮箱获得的输入验证码进行比对,在10分钟内有效
        log.info("authcode返回"+authCodeServiceFeignClient.validateAuthCode(email, code));
        if(!isRegistered(email) && authCodeServiceFeignClient.validateAuthCode(email, code) == 0){

            //1.保存注册信息
            User lagouUser = new User();
            lagouUser.setEmail(email);
            lagouUser.setPassword(password);
            lagouUser.setCreatetime(new Date());
            lagouUser.setLogintime(new Date());
            userDao.save(lagouUser);

            //2.注册成功后，根据<用户邮箱+密码>生成token，用UUID模拟
            String tokenText = email + password;
            UUID uuid = UUID.nameUUIDFromBytes(tokenText.getBytes());

            Token token = new Token();
            token.setEmail(email);
            token.setToken(uuid.toString());
            return tokenDao.save(token);
        }
        return null;
    }

    @Override
    public boolean isRegistered(String email) {
        User lagouUser= userDao.findFirstByEmail(email);
        return lagouUser==null?false:true;
    }

    @Override
    public Token login(String email, String password) {

        User lagouUser = userDao.findFirstByEmail(email);
        //已注册
        if (lagouUser != null && lagouUser.getPassword().equalsIgnoreCase(password)) {
            lagouUser.setLogintime(new Date());
            userDao.save(lagouUser);

            String tokenText = email + password;
            UUID uuid = UUID.nameUUIDFromBytes(tokenText.getBytes());

            Token token = new Token();
            token.setEmail(email);
            token.setToken(uuid.toString());
            return tokenDao.save(token);
        }
        return null;
    }

    @Override
    public String getEmailByToken(String token) {
        Token lagouToken = tokenDao.findFirstByToken(token);
        return token == null ? "NOT FOUND" : lagouToken.getEmail();
    }
}
